package com.yxhl.zoume.core.busticket.ui.fragment;

import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.yxhl.protobuf.OneYxBusInfoRequest;
import com.yxhl.protobuf.ScheduleType;
import com.yxhl.protobuf.YxScheduleEntry;
import com.yxhl.zoume.R;
import com.yxhl.zoume.common.ui.fragment.BaseFragment;
import com.yxhl.zoume.core.busticket.event.ZMTripDateEvent;
import com.yxhl.zoume.core.busticket.model.TicketsQueryOptions;
import com.yxhl.zoume.core.busticket.presenter.BusServicesQueryPresenter;
import com.yxhl.zoume.core.busticket.ui.activity.BusServicesQueryActivity;
import com.yxhl.zoume.core.busticket.ui.adapter.BusServicesAdapter;
import com.yxhl.zoume.core.busticket.view.BusServicesQueryView;
import com.yxhl.zoume.di.component.busticket.BusServiceComponent;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.TimeUtils;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * Created by Xboy on 16/3/16.
 */
public class BusServicesQueryFragment extends BaseFragment implements BusServicesQueryView {
    private static final String TAG = "BusServicesQueryFrag";
    // keys
    private static final String KEY_QUERY_OPTIONS = "QUERY_OPTIONS_FRAGMENT";

    // Calendar Options
    @BindView(R.id.previous_day_tv)
    TextView mPreviousDayTextview;
    @BindView(R.id.selected_day_tv)
    TextView mSelectedDayTextview;
    @BindView(R.id.next_day_tv)
    TextView mNextDayTextview;

    @BindView(R.id.srl_include_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recycler_include_recycler_view)
    RecyclerView mTicketsRecycler;

    // 空页面提示图
    @BindView(R.id.iv_bus_services_no_record)
    ImageView mNoRecordImageView;
    @BindView(R.id.tv_bus_services_no_record)
    TextView mNoRecordTextView;
    @Inject
    BusServicesQueryPresenter queryPresenter;
    BusServicesAdapter busServicesAdapter;
    BusServiceComponent component;
    MaterialDialog dialogForWaitingBusServices;
    private TicketsQueryOptions mQueryOptions;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 提取查询参数f
        Bundle args = getArguments();
        if (null != args) {
            mQueryOptions = (TicketsQueryOptions) args.getSerializable(KEY_QUERY_OPTIONS);
            LOG.v(TAG, "queryOptions : " + mQueryOptions);
        }
        // Event处理
        onRxBusEvent();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        // 绑定View
        queryPresenter.attachView(this);
        // 配置SwipeRefreshLayout
        setupSwipeRefreshLayout();
        // 配置RecyclerView
        setupRecyclerView();
        // 设置当前选中的日期
        refreshSelectedTripDate(mQueryOptions.getTripDate());
        // 查询车票
        queryPresenter.queryBusServices(mQueryOptions.generateParam(), true);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        queryPresenter.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        queryPresenter.onPause();
    }

    @Override
    public void onDestroyView() {
        LOG.e(TAG, "onDestroyView");
        dismissWaitingDialog();
        super.onDestroyView();
        queryPresenter.onDestroy();
    }


    public static BusServicesQueryFragment newInstance(TicketsQueryOptions options) {
        Bundle args = new Bundle();
        args.putSerializable(KEY_QUERY_OPTIONS, options);
        BusServicesQueryFragment fragment = new BusServicesQueryFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private void onRxBusEvent() {
        getSubscription().add(toSubscription(YxScheduleEntry.class,
                new Action1<YxScheduleEntry>() {
                    @Override
                    public void call(YxScheduleEntry scheduleEntry) {

                        ScheduleType scheduleType = scheduleEntry.getType();
                        String sysNo = scheduleEntry.getSysNo();

                        OneYxBusInfoRequest param = OneYxBusInfoRequest.newBuilder()
                                .setType(scheduleType)
                                .setScheduleNo(scheduleEntry.getScheduleNo())
                                .setStartStationCode(scheduleEntry.getStartStationCode())
                                .setEndStationCode(scheduleEntry.getEndStationCode())
                                .setGmtDepart(scheduleEntry.getGmtDepartDate() + " " + scheduleEntry.getGmtDepartTime())
                                .setSysNo(sysNo)
                                .build();

                        switch (scheduleType) {
                            // 定制巴士
                            case V_DIY_BUS:
                                getAppComponent().navigator().navigateToZouMeBusOrder(component.context(), param);
                                break;
                            //固定时刻/新地/大巴网类型巴士
                            default:
                                getAppComponent().navigator().navigateToBusTicketOrder(component.context(), param, scheduleType);
                        }
                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LOG.e(TAG, "throwable=" + throwable.toString());
                        onRxBusEvent();
                    }
                }
        ));

        // 出行日期
        getSubscription().add(toSubscription(ZMTripDateEvent.class,
                new Action1<ZMTripDateEvent>() {
                    @Override
                    public void call(ZMTripDateEvent zmTripDateEvent) {
                        String dateSelected = zmTripDateEvent.getTripDate();
                        refreshSelectedTripDate(dateSelected);
                        queryPresenter.queryBusServices(mQueryOptions.generateParam(dateSelected), true);
                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LOG.e(TAG, "throwable=" + throwable.toString());
                        onRxBusEvent();
                    }
                }
        ));
    }


    private void setupSwipeRefreshLayout() {
        mSwipeRefreshLayout.setColorSchemeResources(
                R.color.swipe_refresh_blue,
                R.color.swipe_refresh_red,
                R.color.swipe_refresh_orange);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                queryPresenter.queryBusServices(mQueryOptions.generateParam(selectedTripDate()), false);
            }
        });
    }

    private void setupRecyclerView() {
        mTicketsRecycler.setLayoutManager(new LinearLayoutManager(component.context()));
        mTicketsRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.set(0, 10, 0, 15);
            }
        });
    }

    @Override
    protected void initializeInjector() {
        component = getComponent(BusServiceComponent.class);
        if (component != null) {
            component.inject(this);
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_bus_tickets_query;
    }

    @Override
    protected void setupToolBar() {
        if (getActivity() instanceof BusServicesQueryActivity) {
            String title = mQueryOptions.getStartCityName() + " - " + mQueryOptions.getArrivalCityName();
            ((BusServicesQueryActivity) getActivity()).setToolbarTitle(title);
        }
    }

    @OnClick(R.id.previous_day_tv)
    void onPreviousDayClick() {
        if (TimeUtils.isToday(selectedTripDate())) {// 时光无法倒流
            return;
        }

        String previousDate = TimeUtils.previousDate(selectedTripDate());
        // 更新选中日期
        refreshSelectedTripDate(previousDate);

        // 查询前一天的车票
        queryPresenter.queryBusServices(mQueryOptions.generateParam(previousDate), true);
    }

    @OnClick(R.id.selected_day_tv)
    void onCalendarClick() {
        getAppComponent().navigator().navigateToCalendar(component.context());
    }

    @OnClick(R.id.next_day_tv)
    void onNextDayClick() {
        String nextDate = TimeUtils.nextDate(selectedTripDate());
        // 更新选中日期
        refreshSelectedTripDate(nextDate);

        // 查询后一天车票
        queryPresenter.queryBusServices(mQueryOptions.generateParam(nextDate), true);
    }

    @Override
    public void renderServices(List<YxScheduleEntry> yxScheduleEntryList) {
        mSwipeRefreshLayout.setRefreshing(false);

        if (0 < yxScheduleEntryList.size()) {
            mNoRecordImageView.setVisibility(View.GONE);
            mNoRecordTextView.setVisibility(View.GONE);
        } else {
            mNoRecordImageView.setVisibility(View.VISIBLE);
            mNoRecordTextView.setVisibility(View.VISIBLE);
        }
        busServicesAdapter = new BusServicesAdapter(yxScheduleEntryList, component.context());
        mTicketsRecycler.setAdapter(busServicesAdapter);
    }

    @Override
    public void waitingForQueryBusServices(boolean isWaiting) {
        if (isWaiting) {
            dialogForWaitingBusServices = new MaterialDialog.Builder(component.context())
                    .content(R.string.dialog_waiting_loading)
                    .progress(true, 0)
                    .canceledOnTouchOutside(false)
                    .show();
        } else {
            dismissWaitingDialog();
        }
    }

    /**
     * 关闭loading框
     */
    private void dismissWaitingDialog() {
        if (null != dialogForWaitingBusServices && dialogForWaitingBusServices.isShowing()) {
            dialogForWaitingBusServices.dismiss();
        }
    }

    private void refreshSelectedTripDate(String tripDate) {
        mSelectedDayTextview.setText(tripDate);
    }

    private String selectedTripDate() {
        return mSelectedDayTextview.getText().toString();
    }


}
